package role

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"

	"gitee.com/hexug/devcloud/mcenter/common/meta"
)

func NewCreateRoleRequest() *CreateRoleRequest {
	return &CreateRoleRequest{
		Features: []*Feature{},
	}
}

func (c *CreateRoleRequest) AddFeature(f *Feature) {
	c.Features = append(c.Features, f)
}

func New() *Role {
	return &Role{
		Meta: meta.NewMeta(),
		Spec: NewCreateRoleRequest(),
	}
}

func NewRole(in *CreateRoleRequest) *Role {
	// TODO 很简陋，无法唯一
	data := meta.NewMeta()
	return &Role{
		Meta: data,
		Spec: in,
	}
}

func NewRoleSet() *RoleSet {
	return &RoleSet{
		Items: []*Role{},
	}
}

func NewQueryRoleRequest() *QueryRoleRequest {
	return &QueryRoleRequest{}
}

func NewDetailRoleRequestByID(id string) *DetailRoleRequest {
	return &DetailRoleRequest{
		DetailType: DESCRIBE_BY_ROLE_ID,
		Value:      id,
	}
}
func NewDetailRoleRequestByName(name string) *DetailRoleRequest {
	return &DetailRoleRequest{
		DetailType: DESCRIBE_BY_ROLE_NAME,
		Value:      name,
	}
}

func NewFeature() *Feature {
	return &Feature{}
}

func (f *Feature) AddEndpointID() error {
	sh := sha1.New()
	if _, err := sh.Write(
		[]byte(
			fmt.Sprintf("%s.%s.%s",
				f.ServiceId,
				f.HttpMethod,
				f.HttPath))); err != nil {
		return err
	}
	f.EndpointId = hex.EncodeToString(sh.Sum(nil))
	return nil
}

func (r *Role) HasFeatrue(serviceId, httpMethod, httPath string) bool {
	for _, f := range r.Spec.Features {
		if ok := f.IsEqual(serviceId, httpMethod, httPath); ok {
			return true
		}
	}
	return false
}

func (r *Role) HasFeatrueByEndpoint(endpointID string) bool {
	for _, f := range r.Spec.Features {
		if f.EndpointId == endpointID {
			return true
		}
	}
	return false
}
func (f *Feature) IsEqual(serviceId, httpMethod, httPath string) bool {
	return f.ServiceId == serviceId &&
		f.HttpMethod == httpMethod &&
		f.HttPath == httPath
}
